package com.dwin.h5.app.utils.http;

import android.util.Log;


import com.dwin.h5.app.models.WeatherModel;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class WeatherRetrofit {

    // 判断是否是Debug模式
//    private static final String BASE_URL_DEV = "http://api.applogin.dwinhmi.com.cn";
    private static final String BASE_URL_DEV = "http://api.map.baidu.com";

    private static String getBaseUrl() {
        return BASE_URL_DEV;
    }

    private static WeatherRetrofit instance = null;

    public static synchronized WeatherRetrofit getInstance() {
        // 这个方法比上面有所改进，不用每次都进行生成对象，只是第一次
        // 使用时生成实例，提高了效率！
        if (instance == null)
            instance = new WeatherRetrofit();
        return instance;
    }

    static Retrofit retrofit;
    static WeatherService service;

    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
        @Override
        public void log(String message) { //打印retrofit日志
            Log.e("RetrofitLog", "retrofitBack = " + message);
        }
    });

    private WeatherRetrofit() {
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder()//okhttp设置部分，此处还可再设置网络参数
                .addInterceptor(loggingInterceptor).build();

        retrofit = new Retrofit.Builder().baseUrl(getBaseUrl())
                .client(client)//此client是为了打印信息
                .addConverterFactory(GsonConverterFactory.create()).build();
        service = retrofit.create(WeatherService.class);
    }

    /**
     * 根据经纬度，获取城市信息
     * @param latLng
     * @param callback
     */
    public static void getLocInfo(String latLng, Callback<WeatherModel> callback) {
        Call<WeatherModel> call = service.getLocInfo("json", latLng, "AB1FYnKMHRR4FWnTjFI3Rla5ZEgnitlQ");
        call.enqueue(callback); // 异步发送请求
    }

}
